package taskserv

import (
	"cm2/service"
	"cm2/service/log"
	"cm2/service/task"
	"cm2/terminal/console/win/global"
	"fmt"

	"github.com/go-xorm/xorm"
)

// RunTaskService 启动任务服务
func RunTaskService() {
	log.DefaultLogger().Info("launching task tcp server service")
	global.TaskServShutdown = make(chan bool, 1)

	tsConfig := service.DefaultConfig["taskServer"].(map[string]interface{})
	tsAddr := tsConfig["addr"].(string)
	tsPort := int(tsConfig["port"].(float64))
	tsAddress := fmt.Sprintf("%s:%d", tsAddr, tsPort)

	tts := task.NewServer(
		service.SId,
		fmt.Sprintf("task tcp server service (%s @ %s)", service.SName, service.SId),
		service.SType,
		tsAddress,
	)
	tts.SetLogger(log.NamedLogger("taskmng"))

	tsRetryConfig := tsConfig["readRetry"].(map[string]interface{})
	tsRetryTimes := int(tsRetryConfig["times"].(float64))
	tsRetryDuration := int(tsRetryConfig["duration"].(float64))
	tts.SetReadRetryParams(tsRetryTimes, tsRetryDuration)
	tts.SetOnReportReceived(service.DefaultJobService().ResolveReport)
	tts.SetLogFn(
		service.DefaultJobService().CreateJobLog,
		service.DefaultJobService().UpdateJobTaskLogState,
	)

	// 注册绑定的worker
	tts.SetClients(service.DefaultConfig["workers"].([]interface{}))

	// 注册为默认的task server
	service.RegisterTaskServer("default", tts)

	go func() {
		tts.Start()
		global.TaskServShutdown <- true
	}()
}

// RunJobService 启动 job service
func RunJobService(jbp *xorm.Engine) {
	jsConfig := service.DefaultConfig["jobService"].(map[string]interface{})
	js := task.NewJobService(service.SId, service.SName)
	js.SetLogger(log.NamedLogger("taskmng"))
	js.SetMaxProc(int(jsConfig["maxproc"].(float64)))
	js.SetJobLogProvider(jbp)

	// 注册为默认的job service
	service.RegisterJobService("default", js)

	js.Start()
}
